/*
 * Copyright 2014 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.qtone.test.pinpoint;

import cn.qtone.qtframe.data.hbase.client.HbaseOperations2;
import com.navercorp.pinpoint.common.hbase.HBaseTables;
import com.navercorp.pinpoint.common.server.util.SpanUtils;
import com.navercorp.pinpoint.web.vo.Range;
import com.navercorp.pinpoint.web.vo.scatter.Dot;
import com.sematext.hbase.wd.AbstractRowKeyDistributor;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author emeroad
 * @author netspider
 */
public class HbaseApplicationTraceIndexDao {

    private static final int APPLICATION_TRACE_INDEX_NUM_PARTITIONS = 32;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HbaseOperations2 hbaseOperations2;

    @Autowired
    @Qualifier("applicationTraceIndexDistributor")
    private AbstractRowKeyDistributor traceIdRowKeyDistributor;

    private int scanCacheSize = 256;

    public void setScanCacheSize(int scanCacheSize) {
        this.scanCacheSize = scanCacheSize;
    }


    private Scan createScan(String applicationName, Range range) {
        return createScan(applicationName, range, true);
    }

    private Scan createScan(String applicationName, Range range, boolean scanBackward) {
        Scan scan = new Scan();
        scan.setCaching(this.scanCacheSize);
        try {
            scan.setTimeRange(range.getFrom(),range.getTo());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(null != applicationName){
            byte[] bApplicationName = Bytes.toBytes(applicationName);
            byte[] traceIndexStartKey = SpanUtils.getTraceIndexRowKey(bApplicationName, range.getFrom());
            byte[] traceIndexEndKey = SpanUtils.getTraceIndexRowKey(bApplicationName, range.getTo());

            if (scanBackward) {
                // start key is replaced by end key because key has been reversed
                scan.setStartRow(traceIndexEndKey);
                scan.setStopRow(traceIndexStartKey);
            } else {
                scan.setReversed(true);
                scan.setStartRow(traceIndexStartKey);
                scan.setStopRow(traceIndexEndKey);
            }
        }

        scan.addFamily(HBaseTables.APPLICATION_TRACE_INDEX_CF_TRACE);
        scan.setId("ApplicationTraceIndexScan");

        // toString() method of Scan converts a message to json format so it is slow for the first time.
        logger.trace("create scan:{}", scan);
        return scan;
    }

    public List<Dot> scanTraceScatterData(String applicationName, Range range, int limit) {
        if (range == null) {
            throw new NullPointerException("range must not be null");
        }
        if (limit < 0) {
            throw new IllegalArgumentException("negative limit:" + limit);
        }
        boolean scanBackward = true;
        logger.debug("scanTraceScatterDataMadeOfDotGroup");
        Scan scan = createScan(applicationName, range, scanBackward);

        TraceIndexScatterMapper3 mapper = new TraceIndexScatterMapper3();
        List<List<Dot>> dotGroupList = hbaseOperations2.findParallel(HBaseTables.APPLICATION_TRACE_INDEX, scan, traceIdRowKeyDistributor, limit, mapper, APPLICATION_TRACE_INDEX_NUM_PARTITIONS);
        List<Dot> list = new ArrayList<>();
        if(null != dotGroupList){
            for(List<Dot> l:dotGroupList){
                list.addAll(l);
            }
        }
        return list;
    }



    public HbaseOperations2 getHbaseOperations2() {
        return hbaseOperations2;
    }

    public void setHbaseOperations2(HbaseOperations2 hbaseOperations2) {
        this.hbaseOperations2 = hbaseOperations2;
    }


    public AbstractRowKeyDistributor getTraceIdRowKeyDistributor() {
        return traceIdRowKeyDistributor;
    }

    public void setTraceIdRowKeyDistributor(AbstractRowKeyDistributor traceIdRowKeyDistributor) {
        this.traceIdRowKeyDistributor = traceIdRowKeyDistributor;
    }
}
